package com.cskaoyan.market.service.admin;

import com.cskaoyan.market.db.domain.MarketRegion;
import com.cskaoyan.market.db.domain.MarketRegionExample;
import com.cskaoyan.market.db.mapper.MarketRegionMapper;
import com.cskaoyan.market.vo.MarketRegionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MarketRegionServiceImpl implements MarketRegionService {

    @Autowired
    MarketRegionMapper regionMapper;

    @Override
    public List<MarketRegionVo> list() {
        //查询整张表，然后按pid分组，通过查看表中内容可知，pid为0代表省
        //查询整张表
        List<MarketRegion> marketRegions = regionMapper.selectByExample(new MarketRegionExample());
        //将表格数据按照pid分组，用map存储
        Map<Integer,List<MarketRegion>> map=groupByPidRegion(marketRegions);
        //用一个list保存整张表
        List<MarketRegionVo> marketRegionVoList=new ArrayList<>();
        //province的pid为0，先获取province列表
        List<MarketRegion> provinces = map.get(0);
        for (MarketRegion province : provinces) {
            //省的children是市list,市的children是区list
            Integer provinceId = province.getId();
            List<MarketRegionVo> cityVoList=new ArrayList<>();
            MarketRegionVo provinceVo=new MarketRegionVo(provinceId,province.getCode(),province.getName(),province.getType(),cityVoList);
            List<MarketRegion> cities = map.get(provinceId);
            for (MarketRegion city : cities) {
                Integer cityId = city.getId();
                List<MarketRegionVo> areaVolist=new ArrayList<>();
                MarketRegionVo cityVo=new MarketRegionVo(cityId,city.getCode(),city.getName(),city.getType(),areaVolist);
                List<MarketRegion> areas = map.get(cityId);
                for (MarketRegion area : areas) {
                    areaVolist.add(new MarketRegionVo(area.getId(),area.getCode(),area.getName(),area.getType(),null));
                }
                cityVoList.add(cityVo);
            }
            marketRegionVoList.add(provinceVo);
        }
        return marketRegionVoList;
    }

    private Map<Integer, List<MarketRegion>> groupByPidRegion(List<MarketRegion> marketRegions) {
        Map<Integer,List<MarketRegion>> map=new HashMap<>();
        for (MarketRegion marketRegion : marketRegions) {
            Integer pid = marketRegion.getPid();
            List<MarketRegion> list=map.get(pid);
            //key是pid，value是所有相同pid的数据list。如果该pid还没存，则新建一个list，存到map中，
            if(list==null){
                list=new ArrayList<>();
            }
            //将当前数据添加到list中
            list.add(marketRegion);
            map.put(pid,list);
        }
        return map;
    }
}

